package com.example.navigationdemo.nav;

import android.os.Bundle;
import android.os.PersistableBundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;

import com.example.navigationdemo.R;
import com.example.navigationdemo.nav.model.Destination;
import com.example.navigationdemo.nav.utils.AppConfig;
import com.example.navigationdemo.nav.utils.NavGraphBuilder;
import com.example.navigationdemo.nav.view.AppBottomBar;
import com.example.navigationdemo.nav.view.AppLottieBottomBar;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author: tuyrt7 on 2020/9/3.
 */
public class LottieActivity extends AppCompatActivity implements  AppLottieBottomBar.OnSelectItemListener {

    private NavController mNavController;
    private AppLottieBottomBar mBottomBar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lottie);
        mBottomBar = findViewById(R.id.lottieBar);

        /**
         *  关联配置文件和 Navigation
         */
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.nav_host);
        mNavController = NavHostFragment.findNavController(fragment);
        NavGraphBuilder.build(this, fragment.getChildFragmentManager(), mNavController, fragment.getId());

        mBottomBar.setOnSelectItemListener(this);
    }


//    @Override
//    public void onBackPressed() {
//        int currentId = mNavController.getCurrentDestination().getId();
//        int homeId = mNavController.getGraph().getStartDestination();
//        //不是起始节点，就退回起始节点
//        if (currentId != homeId) {
//            mBottomBar.setSelectedItemId(homeId);
//            return;
//        }
//        finish();
//    }

    @Override
    public void onSelectItem(int id) {
        Log.d("aaaa", "Destination id: "+id);
        mNavController.navigate(id);
    }


    @Override
    public void onBackPressed() {
        int currentPageId = mNavController.getCurrentDestination().getId();
        int homeDestId = mNavController.getGraph().getStartDestination();
        if (currentPageId != homeDestId) {
            //不是首页，按了返回键，就回到首页
            mBottomBar.setSelectedItemId(homeDestId);
            return;
        }
        //否则 finish，此处不宜调用onBackPressed。因为navigation会操作回退栈,切换到之前显示的页面。
        finish();
    }
}
